package com.zihan.service;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.BaseFont;
import org.springframework.stereotype.Service;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.Map;

@Service
public class SimplePdfCertificateService {

    // 渲染HTML模板
    private String renderHtmlTemplate(String templatePath, Map<String, String> data) throws IOException {
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(templatePath);
        if (inputStream == null) {
            throw new IOException("找不到模板文件: " + templatePath);
        }
        String html = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
        for (Map.Entry<String, String> entry : data.entrySet()) {
            html = html.replace("{{" + entry.getKey() + "}}", entry.getValue());
        }
        return html;
    }

    public File generatePdf(String name, String activityName) throws Exception {
        String date = LocalDate.now().toString();
        Map<String, String> data = Map.of(
            "name", name, 
            "activityName", activityName, 
            "date", date
        );
        
        String html = renderHtmlTemplate("certificate.html", data);
        
        // 转换为严格的XHTML格式
        String xhtml = convertToXhtml(html);
        
        File pdfFile = File.createTempFile("certificate_", ".pdf");

        // 使用 Flying Saucer 生成 PDF，支持HTML样式和中文字体
        try (FileOutputStream fos = new FileOutputStream(pdfFile)) {
            ITextRenderer renderer = new ITextRenderer();

            // 添加中文字体支持
            try {
                // 多系统常见中文字体路径
                String[] fontPaths = {
                        // Windows 常见字体
                        "C:/Windows/Fonts/simsun.ttc",        // 宋体
                        "C:/Windows/Fonts/simhei.ttf",        // 黑体
                        "C:/Windows/Fonts/msyh.ttc",          // 微软雅黑
                        "C:/Windows/Fonts/msyhbd.ttc",        // 微软雅黑 Bold
                        "C:/Windows/Fonts/KaiTi.ttf",         // 楷体
                        "C:/Windows/Fonts/FangSong.ttf",      // 仿宋
                        "C:/Windows/Fonts/SIMLI.TTF",         // 隶书
                        "C:/Windows/Fonts/STZHONGS.TTF",      // 华文中宋
                        "C:/Windows/Fonts/STSONG.TTF",        // 华文宋体

                        // macOS 常见字体
                        "/System/Library/Fonts/PingFang.ttc",           // 苹方
                        "/System/Library/Fonts/STHeiti Light.ttc",      // 华文黑体
                        "/System/Library/Fonts/STSong.ttc",             // 华文宋体
                        "/Library/Fonts/Songti.ttc",                    // 宋体
                        "/Library/Fonts/Heiti.ttc",                     // 黑体
                        "/Library/Fonts/Hiragino Sans GB.ttc",          // 冬青黑体简体中文

                        // Linux 常见字体
                        "/usr/share/fonts/truetype/arphic/uming.ttc",       // 文鼎明体
                        "/usr/share/fonts/truetype/arphic/ukai.ttc",        // 文鼎楷体
                        "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",     // 文泉驿正黑
                        "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",   // 文泉驿微米黑
                        "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", // Noto Sans CJK
                        "/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc", // Noto Serif CJK
                        "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"   // 兜底英文字体
                };
                boolean fontLoaded = false;
                for (String fontPath : fontPaths) {
                    try {
                        renderer.getFontResolver().addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                        System.out.println("成功加载字体: " + fontPath);
                        fontLoaded = true;
                        break;
                    } catch (Exception ignored) {
                        // 继续尝试下一个字体
                    }
                }

                if (!fontLoaded) {
                    System.out.println("警告: 无法加载任何中文字体，中文可能显示为方块");
                }
            } catch (Exception e) {
                System.out.println("字体加载异常: " + e.getMessage());
            }

            renderer.setDocumentFromString(xhtml);
            renderer.layout();
            renderer.createPDF(fos);
        }

        return pdfFile;
    }
    
    // 将HTML转换为XHTML格式（简化版本）
    private String convertToXhtml(String html) {
        return html;
    }
}
